package MediaOnline.VideoPlayer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.security.auth.DestroyFailedException;
import javax.security.auth.Destroyable;

import android.app.Activity;
import android.content.SharedPreferences;
import android.util.Log;

public class LikeMovie implements Destroyable {

	private HashMap<String, String> likes = new HashMap<String, String>();
	private Activity act;

	public LikeMovie(Activity act) {
		this.act = act;
		loadFromSystem();
	}

	public void loadFromSystem() {
		SharedPreferences customSharedPreference = act.getSharedPreferences(
				"LikeSharedPrefs", act.MODE_PRIVATE);
		Map<String, ?> temp = customSharedPreference.getAll();
		for (String s : temp.keySet()) {
			likes.put(s, temp.get(s).toString());
		}
	}

	private void saveToSystem() {
		SharedPreferences customSharedPreference = act.getSharedPreferences(
				"LikeSharedPrefs", act.MODE_PRIVATE);
		delAllSharedPrefs();
		for (String s : likes.keySet()) {
			customSharedPreference.edit()
					.putString(s, likes.get(s)).commit();
		}
	}

	public void addLiked(String url, String title) {
		if (!likes.containsKey(url)) {
			likes.put(url, title);
			saveToSystem();
		}
	}

	public Boolean exitsLikes(int id) {
		return likes.containsKey(id);
	}

	public void clear() {
		likes.clear();
	}

	public List<String> getList() {
		List<String> temp = new ArrayList<String>();
		for (String s : likes.values()) {
			temp.add(s);
		}
		return temp;
	}

	public String getId(int idx) {
		ArrayList<String> temp = new ArrayList<String>(likes.keySet());
		return temp.get(idx);
	}

	public String getName(int idx) {
		String id = getId(idx);
		return likes.get(id);
	}

	public void deleteLikes(Integer[] idx) { // Gia su mang la 1 day thu tu bai
		ArrayList<String> temp = new ArrayList<String>(likes.keySet());
		for (int i = idx.length - 1; i >= 0; i--) {
			temp.remove((int) idx[i]);
			Log.d("idx:_______________", idx[i].toString());
		}

		HashMap<String, String> likes1 = new HashMap<String, String>();
		String k;
		String v;
		for (int i = 0; i < temp.size(); i++) {
			k = temp.get(i);
			v = likes.get(k);
			likes1.put(k, v);
		}

		likes = likes1;
		saveToSystem();
	}
	
	  // Xoa tat cac cac preference
	private boolean delAllSharedPrefs() {
	  SharedPreferences likelist = act.getSharedPreferences("LikeSharedPrefs",Activity.MODE_PRIVATE);
	  SharedPreferences.Editor edit = likelist.edit(); edit.clear();
	  edit.commit(); return true; }
	 
	//
	public void destroy() throws DestroyFailedException {
		// TODO Auto-generated method stub
		saveToSystem();
	}

	public boolean isDestroyed() {
		// TODO Auto-generated method stub
		return false;
	}

}
